#Load Libraries
library(rbounds)
library(exactRankTests)
library(sensitivitymw)

rm(list=ls())


###################################################################
# General Election
###################################################################
setwd("~/Documents/Black Mayors/Replication File/Matches")
load("MatchAll.RData")

out.tr <- data.match.all$black_turnout[data.match.all$black==1]
out.co <- data.match.all$black_turnout[data.match.all$black==0]

N <- length(c(out.tr, out.co))

rank_out <- wilcox.exact(out.tr, out.co, paired=TRUE, distribution="exact", conf.int=TRUE, alternative="two.sided")
rank_out$p.value
rank_out$conf.int
rank_out$estimate

# M Statistic Sens Analysis
senmwCI((out.tr - out.co), gamma= 4.01, method="p")
Gamma <- 1.69

col1 <- c(rank_out$estimate, rank_out$conf.int, rank_out$p.value, Gamma, N)
col1

objects()
rm(data.match.all, Gamma, N, out.co, out.tr, rank_out)

###################################################################
# Runoff 
###################################################################
setwd("~/Documents/Black Mayors/Replication File/Matches")
load("MatchRunOff.RData")

out.tr <- data.match.runoff$black_turnout[data.match.runoff$black==1]
out.co <- data.match.runoff$black_turnout[data.match.runoff$black==0]

cbind(out.tr, out.co)
out.tr <- out.tr[-15]
out.co <- out.co[-15]

N <- length(c(out.tr, out.co))

rank_out <- wilcox.exact(out.tr, out.co, paired=TRUE, distribution="exact", conf.int=TRUE, alternative="two.sided")
rank_out$p.value
rank_out$conf.int
rank_out$estimate

# M Statistic Sens Analysis
senmwCI((out.tr - out.co), gamma=1, method="p")
senmwCI((out.tr - out.co), gamma= 4.01, method="p")
Gamma <- 4.01

col2 <- c(rank_out$estimate, rank_out$conf.int, rank_out$p.value, Gamma, N)
col2

objects()
rm(data.match.runoff, Gamma, N, out.co, out.tr, rank_out)

###################################################################
# Run Gen Elect Race Match
###################################################################
setwd("~/Documents/Black Mayors/Replication File/Matches")
load("MatchRunOff_Gen.RData")

out.tr <- data.match.runoff$black_turnout[data.match.runoff$black==1]
out.co <- data.match.runoff$black_turnout[data.match.runoff$black==0]

N <- length(c(out.tr, out.co))

rank_out <- wilcox.exact(out.tr, out.co, paired=TRUE, distribution="exact", conf.int=TRUE, alternative="two.sided")
rank_out$p.value
rank_out$conf.int
rank_out$estimate

# M Statistic Sens Analysis
senmwCI((out.tr - out.co), gamma=1, method="p")
senmwCI((out.tr - out.co), gamma= 2.95, method="p")
Gamma <- 2.95

col3 <- c(rank_out$estimate, rank_out$conf.int, rank_out$p.value, Gamma, N)
col3

setwd("~/Documents/Black Mayors/Replication File")
source("print_tab_match.R")

print.table(col1, col2, col3)


